#import "PluginEchatPlugin.h"
#import <EchatVisitorPort/EchatVisitorPort.h>

#define IS_NIL(_obj)  ((nil == _obj) || [_obj isKindOfClass:[NSNull class]] || [_obj isEqual:[NSNull null]])

@implementation PluginEchatPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_plugin_echat" binaryMessenger:[registrar messenger]];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    PluginEchatPlugin* instance = [[PluginEchatPlugin alloc] initWithViewController:viewController];
    [registrar addMethodCallDelegate:instance channel:channel];
    [registrar addApplicationDelegate:instance];
    
    instance.channel = channel;
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"registerApp" isEqualToString:call.method]) {
      NSString *appId = call.arguments[@"appId"];
      NSString *appSecret = call.arguments[@"appSecret"];
      [self registerAppId:appId appSecret:appSecret];
      result(@(YES));
  } else if ([@"openEchatSessionWindow" isEqualToString:call.method]) {
      [self openEchatSessionWindow:call.arguments];
      result(@(YES));
  } else if ([@"getUnReadMsgCount" isEqualToString:call.method]) {
      NSInteger unreadCount = [self getUnReadMsgCount];
      result(@(unreadCount));
  } else if ([@"getLastMessage" isEqualToString:call.method]) {
      NSDictionary *msgDic = [self getLastMessage];
      result(msgDic);
  } else if ([@"closeCurrentConversation" isEqualToString:call.method]) {
      [self closeCurrentConversationComplete:^{
          result(@(YES));
      } failure:^{
          result(@(NO));
      }];
  } else if ([@"logout" isEqualToString:call.method]) {
      [self logout];
      result(@(YES));
  } else if ([@"cleanMemory" isEqualToString:call.method]) {
      [self cleanMemory];
      result(@(YES));
  } else if ([@"cleanAllMemory" isEqualToString:call.method]) {
      [self cleanAllMemory];
      result(@(YES));
  } else {
    result(FlutterMethodNotImplemented);
  }
}

/// 初始化一洽SDK
/// @param appId App ID
/// @param appSecret App 秘钥
- (void)registerAppId:(NSString*) appId appSecret:(NSString*) appSecret {
    [EchatSDK AppID:appId AppSecret:appSecret];
}

/// 打开会话窗口
/// @param options 会话参数配置
- (void)openEchatSessionWindow:(NSDictionary *)options {
    NSDictionary *paramDict = options;
    Echat_accessConditions * accessCondition;
    if (IS_NIL(options) || options.count == 0) {
        accessCondition = [EchatSDK getLastCondition];
    } else {
        accessCondition = [[Echat_accessConditions alloc]init];
        if ([paramDict objectForKey:@"uid"]){
            accessCondition.uid = paramDict[@"uid"];
        }
        if ([paramDict objectForKey:@"metaData"]){
            accessCondition.metaData = paramDict[@"metaData"];
        }
        if ([paramDict objectForKey:@"myData"]){
            accessCondition.myData = paramDict[@"myData"];
        }
        if ([paramDict objectForKey:@"lan"]){
            accessCondition.lan = paramDict[@"lan"];
        }
        if ([paramDict objectForKey:@"routeEntranceId"]){
            accessCondition.routeEntranceId = paramDict[@"routeEntranceId"];
        }
        /// 图文消息
        if ([paramDict objectForKey:@"visEvt"]){
            NSDictionary *visEvtDict = paramDict[@"visEvt"];
            if (IS_NIL(visEvtDict) || visEvtDict.count == 0) {return;}
            
            Echat_visEvtModel *visEvt = [[Echat_visEvtModel alloc] init];
            if ([visEvtDict objectForKey:@"eventId"]){
                visEvt.eventId = visEvtDict[@"eventId"];
            }
            if ([visEvtDict objectForKey:@"title"]){
                visEvt.title = visEvtDict[@"title"];
            }
            if ([visEvtDict objectForKey:@"content"]){
                visEvt.content = visEvtDict[@"content"];
            }
            if ([visEvtDict objectForKey:@"imageUrl"]){
                visEvt.imageUrl = visEvtDict[@"imageUrl"];
            }
            if ([visEvtDict objectForKey:@"urlForVisitor"]){
                visEvt.urlForVisitor = visEvtDict[@"urlForVisitor"];
            }
            if ([visEvtDict objectForKey:@"urlForStaff"]){
                visEvt.urlForStaff = visEvtDict[@"urlForStaff"];
            }
            if ([visEvtDict objectForKey:@"memo"]){
                visEvt.memo = visEvtDict[@"memo"];
            }
            if ([visEvtDict objectForKey:@"urlEnableForVisitor"]){
                visEvt.urlEnableForVisitor = visEvtDict[@"urlEnableForVisitor"];
            }
            if ([visEvtDict objectForKey:@"visibility"]){
                visEvt.visibility = visEvtDict[@"visibility"];
            }
            if ([visEvtDict objectForKey:@"customizeMsgType"]){
                visEvt.customizeMsgType = visEvtDict[@"customizeMsgType"];
            }
            if ([visEvtDict objectForKey:@"dedup"]){
                visEvt.dedup = visEvtDict[@"dedup"];
            }
            accessCondition.visEvt = visEvt;
        }
        if ([paramDict objectForKey:@"echatTag"]){
            accessCondition.echatTag = paramDict[@"echatTag"];
        }
        if ([paramDict objectForKey:@"pushInfo"]){
            accessCondition.pushInfo = paramDict[@"pushInfo"];
        }
        if ([paramDict objectForKey:@"acdStaffId"]){
            accessCondition.acdStaffId = paramDict[@"acdStaffId"];
        }
        if ([paramDict objectForKey:@"acdType"]){
            accessCondition.acdType = paramDict[@"acdType"];
        }
    }
    
    EchatViewController * chatVC = [[EchatViewController alloc]initWithAccess:accessCondition];
    EchatNavController * nav = [[EchatNavController alloc]initWithRootViewController:chatVC];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.viewController presentViewController:nav animated:YES completion:nil];
}

/// 未读消息总数
- (NSInteger)getUnReadMsgCount {
    return [EchatSDK getUnReadMsgCount];
}

/// 获取最后一条消息
- (NSDictionary *)getLastMessage {
    Echat_MsgModel *msgModel = [EchatSDK getLastMsg];
    
    NSDictionary *msgDict = @{
        @"title": msgModel.title ?: @"",
        @"content": msgModel.content ?: @"",
        @"isNeededLocalPush": @(msgModel.isNeededLocalPush),
        @"msgType": msgModel.msgType ? @(msgModel.msgType): @(0),
    };
    
    return msgDict;
}

/// 关闭连接
/// @param complele 成功回调
/// @param fail 失败回调
- (void)closeCurrentConversationComplete:(dispatch_block_t)complele failure:(dispatch_block_t)fail {
    [EchatSDK closeCurrentConversationComplete:complele failure:fail];
}

/// 退出登录
- (void)logout {
    [EchatSDK logout];
}

/// 清理大文件
- (void)cleanMemory {
    [EchatSDK cleanMemory];
}

/// 清理所有文件
- (void)cleanAllMemory {
    [EchatSDK cleanAllMemory];
}

@end
